package common.controller;

import implementor.GinImplementor;
import implementor.GinItemsImplementor;
import implementor.PurchaseOrderImpl;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import utility.AppUtilities;
import utility.Constants;
import utility.Validater;
import utility.ViewUtilities;

import model.GinItems;
import model.Material;

import common.view.GinView;


import dao.GinDao;
import dao.GinItemsDao;
import dao.PurchaseOrderDao;
import dbhandelling.Connections;
import dto.Gin;

import dto.MaterialSpecification;

public class GinController implements ActionListener{
	private Gin model;
	private GinView view;
	private Vector<GinItems> ginitem;
	private static int srNo=1;
	private MaterialAdderController cntrl;
	
	public GinController(GinView view, Gin model) throws Exception
	{
		this.model=model;
		this.view=view;
		view.actionlisteners(this);
		ginitem=new Vector<GinItems>();
		cntrl=new MaterialAdderController(view.getmAdder(), null);
		view.getmAdder().getBtnAdd().addActionListener(this);
		AppUtilities.fillProjectNameCombo(view.getCbcbProjectName());
		AppUtilities.fillPurchaseOrderCombo(view.getCbpoNumber());
		
	}

	private void addInTable()
	 {
		  //*************************Get the material object from the adder****************************//
		  // from that material object,set the spec code and mcode of Gin Items.
		  
		   Material material = cntrl.getModel();
		   GinItems ginItem = new GinItems();
		   ginItem.setModelMaterial(material);
		   ginItem.setmCode(material.getMCode());
		   ginItem.setSpecCode(material.getCurrentSpecs().getAutoSpecCode());
	//**************************************************************************************************//	   
		   
		    //******Get the po quantity for that Gin Item*******************************************//
		   // Querry the poItem table and get the po qty corresponding to that mcode,speccode,po number
		    PurchaseOrderDao pDao=new PurchaseOrderImpl();
		    String poNo=view.getCbpoNumber().getSelectedItem().toString();
		    double poQty= pDao.getPoQty(poNo, material.getMCode(),material.getCurrentSpecs().getAutoSpecCode());
		    
		    
		    //***************************Add in table************************************************//
		    ginItem.setModelpoQty(poQty);
		    ginItem.setmReceivedQuant(Double.parseDouble(view.getmAdder().getTfAmount().getText().trim()));
		    ginItem.setmSendQty(Double.parseDouble(view.getTfSendQty().getText().trim()));
		    double rejectedqty=(Double.parseDouble(view.getTfSendQty().getText()))-(Double.parseDouble(view.getTfRecievedQty().getText()));
		    DefaultTableModel dm=(DefaultTableModel) view.getTable().getModel();
		    Material tempm=ginItem.getModelMaterial();
		    MaterialSpecification specs= ginItem.getModelMaterial().getCurrentSpecs();
		   
		   dm.addRow(new Object[]{srNo++,tempm.getMname(),specs.getmSpecs(),
				   ginItem.getModelpoQty(),ginItem.getmSendQty(),ginItem.getmReceivedQuant(),rejectedqty});
		   
		  
		   //*******************Add in vector**************************************************//
		   ginitem.add(ginItem);
		 
	 }
	
	
	
	private void reactToSave() throws Exception
	 {
		Connection con =Connections.getMyConnection();
		try {
			con.setAutoCommit(false);
			int ginId= this.saveToGin();
			System.out.println(ginId+"this is Id");
			this.saveToGinItems(ginId);
		} catch (Exception e) {
			con.rollback();
		
			e.printStackTrace();
		}
		con.commit();
		con.setAutoCommit(true);
	 }
	
	
	private int saveToGin() throws Exception
	{
		GinDao gDao=new GinImplementor();
		model=new Gin();
		model.setPoNumber(view.getCbpoNumber().getSelectedItem().toString());
		model.setGinDate(ViewUtilities.convert(view.getTextFieldGinDate().getText().trim()));
		model.setChNo(view.getTfchNo().getText().trim());
		model.setChDate(ViewUtilities.convert(view.getTextFieldChalanDate().getText()));
		model.setIdProject(AppUtilities.getProjectId(view.getCbcbProjectName().getSelectedItem().toString()));
		model.setIdCostCenter(0);
		model.setVehicalNo(view.getTfvehicalNumber().getText().trim());
		model.setStatus(Constants.ACTIVE);
		
		gDao.add(model);
		int autoginNo= gDao.getautoginNo();
		
		return autoginNo;
		
	}
	
	
	private void saveToGinItems(int autoginno) throws  Exception
	{
	   
		int i =0;
		for(;i<this.ginitem.size();i++)
			this.ginitem.get(i).setGinNo(autoginno);
		
		GinItemsDao ginItemsDao = new GinItemsImplementor();
		for(i=0;i<ginitem.size();i++)
			ginItemsDao.add(this.ginitem.get(i));
	   
	}
	
	private void delete(int row)
	{
		JTable table=view.getTable();
		DefaultTableModel dm = (DefaultTableModel) table.getModel();
		dm.removeRow(row);
		ginitem.remove(row);
	}
	
	public void fillViewFfromModel()
	{
		view.getTfchNo().setText(model.getChNo()+"");
		
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
	   String k=arg0.getActionCommand();
	   if(k.equals("GinDate"))
	   {
		   ViewUtilities.makeDateComponent(view.getTextFieldGinDate());
	   }
	   if(k.equals("ChalanDate"))
	   {
		   ViewUtilities.makeDateComponent(view.getTextFieldChalanDate());
	   }
	   if(k.equals("Save"))
	   {
		   try {
				//Validater val = new Validater(view);
				//String message = val.validateForEmpty();
				//if(message.equals(""))
				{
				  reactToSave();
				JOptionPane.showMessageDialog(null,"Successfully Saved!");
				//val.refresh();
				}
			
				//else
					//JOptionPane.showMessageDialog(null,message);
				
			} catch (Exception e1) {
				JOptionPane.showMessageDialog(null,"Failed To Save!");
				e1.printStackTrace();
			}
	   }
		
	   if(k.equals("mAdderAdd"))
		{
			 cntrl.changeModel();
			this.addInTable();
		}
	}

	
	
	
}
